<template>
    <el-dialog draggable title="SQL编辑器" :width="920"
			v-model="show" :close-on-click-modal="false" @close="emit('update:show', false)">
		<div class="dialog-content">
            <CodeMirrorCore :content="content" mode="text/x-sql" ref="cm"
             :dbType="dbType" :keywords="keywords"></CodeMirrorCore>
        </div>
        <template #footer>
            <el-button size="small" type="primary" @click="submit">保存</el-button> 
        </template>
    </el-dialog>
</template>

<script setup>
import CodeMirrorCore from '/src/components/CodeMirrorCore'
import {post} from '/src/utils/http'
import { ElMessage } from 'element-plus'
import { computed, watch,defineProps, defineEmits,defineExpose, onMounted, toRefs, nextTick, ref } from 'vue'

const props = defineProps({
    show:Boolean,
    content: String,
    dbType: String,
    dbConnStr: String,
    keywords: Object
})

const { show,content,dbType,dbConnStr,keywords } = toRefs(props)

const emit = defineEmits(['callback'])

const cm = ref()

defineExpose({ 
    append: (sql)=> cm.value.append(sql),
    clearHistory: ()=> cm.value.clearHistory,
    getSelectionOrValue: ()=>cm.value.getSelectionOrValue,
})

function submit(){
    var sql =  cm.value.getSelectionOrValue()
    var param = { 
        DbConnStr: dbConnStr.value,
        sqls: dbType.value == 'Sqlserver' ? sql.split(/\nGO\n/i): [sql]
    }
    
    post(`/api/${dbType.value}/RunSql`, param).then((res) => {
        if(res && res.flag) { 
            content.value = ''
            emit('update:show', false)
        } else {
            ElMessage({ 
                message: res.logs.join(','),
                type: 'error',
            })
        }
    })
}

watch(() => [show.value, content.value], ([s1,s2],[o1,o2]) => {
    nextTick(() => {
        if(s1 && s1 != o1) {
            cm.value.clearHistory()
        }
        if(s2 != o2) {
            cm.value.setValue(s2)
        }
    })
})

</script>
